package cn.topevery.garden.wapi.controller;

import cn.topevery.garden.dal.dao.GreFileDao;
import cn.topevery.garden.dal.dao.impl.GreTreeFamousDaoImpl;
import cn.topevery.garden.dal.logic.CommunityLogic;
import cn.topevery.garden.dal.logic.GreFileLogic;
import cn.topevery.garden.dal.logic.GreTreeFamousLogic;
import cn.topevery.garden.dal.logic.GreTreeFamousRecordLogic;
import cn.topevery.garden.entity.dto.GreTreeFamousDTO;
import cn.topevery.garden.entity.po.Community;
import cn.topevery.garden.entity.po.GreFile;
import cn.topevery.garden.entity.po.GreTreeFamous;
import cn.topevery.garden.entity.query.CommunityQuery;
import cn.topevery.garden.entity.query.GreTreeFamousQuery;
import cn.topevery.garden.entity.query.GreTreeFamousRecordQuery;
import cn.topevery.garden.entity.vo.CommunityVO;
import cn.topevery.garden.entity.vo.GreTreeFamousRecordVO;
import cn.topevery.garden.entity.vo.GreTreeFamousVO;
import cn.topevery.garden.wapi.utils.CoordinateTransHelper;
import cn.topevery.garden.wapi.utils.LocationTrans;
import com.github.dozermapper.core.Mapper;
import hw.topevery.basis.entity.po.SysUser;
import hw.topevery.framework.db.entity.DataPager;
import hw.topevery.framework.dto.PointDto;
import hw.topevery.framework.util.ExcelUtil;
import hw.topevery.framework.web.JsonResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.*;
import java.util.stream.Collectors;

import static cn.topevery.garden.entity.po.GreFile.TYPE_GRE_TREE_FAMOUS;

/**
 * 古树名木表
 *
 * @author code-generate
 * @date 2022-01-05
 */
@Api(tags = "古树名木表")
@RestController
@RequestMapping("/greTreeFamous")
public class GreTreeFamousController extends BaseController {

    @Autowired
    private Mapper mapper;

    @Autowired
    GreTreeFamousLogic greTreeFamousLogic;

    @Autowired
    GreTreeFamousLogic iGreTreeFamousService;

    @Autowired
    GreFileLogic greFileLogic;

    @Autowired
    GreTreeFamousRecordLogic greTreeFamousRecordLogic;

    @Autowired
    CommunityLogic communityLogic;

    @Autowired
    GreFileDao greFileDao;

    @Autowired
    private CommunityLogic communityService;

    @Autowired
    private GreTreeFamousDaoImpl greTreeFamousDao;

    /**
     * 获取古树名木表分页列表
     *
     * @param query
     * @return
     */
    @ApiOperation(value = "获取古树名木记录表页列表")
    @PostMapping("/getList")
    public JsonResult<DataPager<GreTreeFamousVO>> getList(@RequestBody GreTreeFamousQuery query) {
        DataPager<GreTreeFamousVO> res = greTreeFamousLogic.listPage(query);
        List<GreTreeFamousVO> records = res.records;
        if (records != null && !records.isEmpty()) {
            records.stream().peek(temp -> {
                temp.setFileList(greFileLogic.getListByMainId(temp.getId(), TYPE_GRE_TREE_FAMOUS));
            }).collect(Collectors.toList());
        }
        return JsonResult.ok(res);
    }

    @PostMapping(value = "/getRecordList")
    @ApiOperation(value = "获取古树名木历史信息")
    public JsonResult<DataPager<GreTreeFamousRecordVO>> getRecordList(@RequestBody GreTreeFamousRecordQuery greTreeFamousRecordQuery) {
        DataPager<GreTreeFamousRecordVO> res = greTreeFamousLogic.getRecordList(greTreeFamousRecordQuery);
        List<GreTreeFamousRecordVO> records = res.records;
        if (records != null && !records.isEmpty()) {
            res.records = (records.stream().peek(temp -> {
                temp.setFileList(greFileLogic.getListByMainRecordId(temp.getId(), TYPE_GRE_TREE_FAMOUS));
            }).collect(Collectors.toList()));
        }
        return JsonResult.ok(res);
    }

    @ApiOperation("新增/编辑 古树名木表信息")
    @PostMapping("/insert")
    public JsonResult<Boolean> insert(@Valid @RequestBody GreTreeFamousDTO dto) {
        Calendar cal = Calendar.getInstance();
        int year = cal.get(Calendar.YEAR);
        dto.setYear(year).setState(false).setTreeId(UUID.randomUUID().toString());
        dto.setObjName("6");
        GreTreeFamous greTreeFamous = greTreeFamousLogic.insertEntity(getUser().id.toString(), mapper.map(dto, GreTreeFamous.class));
        dto.setId(greTreeFamous.getId());
        if (dto.getFileList() != null && !dto.getFileList().isEmpty()) {
            List<GreFile> collect = dto.getFileList().stream().peek(temp -> {
                temp.setDataType(TYPE_GRE_TREE_FAMOUS);
                temp.setMainId(dto.getId());
                temp.setMainRecordId(dto.getId());
                temp.setDbStatus(false);
            }).collect(Collectors.toList());
            for (GreFile greFile : collect) {
                greFileDao.saveOrUpdate(getUser().id.toString(), greFile);
            }
        }
        return JsonResult.ok(true);
    }

    @ApiOperation("新增/编辑 古树名木表信息")
    @PostMapping("/update")
    public JsonResult<Boolean> update(@Valid @RequestBody GreTreeFamousDTO dto) {
        Calendar cal = Calendar.getInstance();
        int year = cal.get(Calendar.YEAR);
        dto.setYear(year);
        if (dto.getId() == null) {
            dto.setState(false);
            dto.setTreeId(UUID.randomUUID().toString());
        }
        dto.setAvgCrown((dto.getEastWestCrown() + dto.getNorthSouthCrown()) / 2);
        greTreeFamousLogic.saveOrUpdate(getUser().id.toString(), mapper.map(dto, GreTreeFamous.class));
        greFileDao.deleteByMainId(dto.getId(), getUser().id.toString(), TYPE_GRE_TREE_FAMOUS);
        if (dto.getFileList() != null && !dto.getFileList().isEmpty()) {
            List<GreFile> collect = dto.getFileList().stream().peek(temp -> {
                temp.setDataType(TYPE_GRE_TREE_FAMOUS);
                temp.setMainId(dto.getId());
                temp.setMainRecordId(dto.getId());
                temp.setDbStatus(false);
            }).collect(Collectors.toList());
            for (GreFile greFile : collect) {
                greFileDao.saveOrUpdate(getUser().id.toString(), greFile);
            }
        }
        return JsonResult.ok(true);
    }

    @GetMapping(value = "/getById")
    @ApiOperation(value = "通过id获取树木信息")
    public JsonResult<GreTreeFamous> getById(@RequestParam Integer id) {
        GreTreeFamous res = greTreeFamousLogic.getById(id);
        if (res != null) {
            res.setFileList(greFileLogic.getListByMainId(res.getId(), TYPE_GRE_TREE_FAMOUS));
        }
        return JsonResult.ok(res);
    }

    @ApiOperation("通过Id获取详情")
    @GetMapping("/getInfoById")
    public JsonResult<GreTreeFamous> getInfoById(@RequestParam Integer id) {
        GreTreeFamous entity = greTreeFamousLogic.getEntity(id);
        PointDto pointDto = CoordinateTransHelper.wgs84Bd09(entity.getLng(), entity.getLat());
        entity.setLng(pointDto.getLng());
        entity.setLat(pointDto.getLat());
        entity.setFileList(greFileLogic.getListByMainId(entity.getId(), TYPE_GRE_TREE_FAMOUS));
        return JsonResult.ok(entity);
    }

    @ApiOperation("根据自增ID批量删除")
    @PostMapping("/deleteBatchById")
    public JsonResult<Boolean> deleteBatchById(@RequestBody Integer[] ids) {
        greTreeFamousLogic.deleteBatchById(getUser().id.toString(), ids);
        return JsonResult.ok(true);
    }

    @ApiOperation("导出古树名木表信息")
    @GetMapping("/export")
    public void export(GreTreeFamousQuery query, HttpServletResponse response) {
        List<GreTreeFamousVO> list = greTreeFamousLogic.listPage(query).records;
        ExcelUtil.exportExcel(list, "古树名木表", "sheet1", GreTreeFamousVO.class, "古树名木表", response);
    }

    @GetMapping(value = "/getSituation")
    @ApiOperation(value = "获取绿化资源概况")
    public JsonResult<Map<String, Object>> getSituation() {
        Map<String, Object> map = iGreTreeFamousService.getSituation();
        return JsonResult.ok(map);
    }

    @GetMapping(value = "/getAreaCountStat")
    @ApiOperation(value = "获取区域数量统计")
    public JsonResult<List<Map<String, Object>>> getAreaStat() {
        List<Map<String, Object>> map = iGreTreeFamousService.getAreaCountStat();
        return JsonResult.ok(map);
    }

    @GetMapping(value = "/getAllTreeFamousForMap")
    @ApiOperation(value = "获取所有古树名木,地图浏览使用")
    public JsonResult getAllTreeFamousForMap(int famous_type_id) {
        List<Map<String, Object>> res = iGreTreeFamousService.getAllTreeFamousForMap(famous_type_id);
        res.forEach(a -> {
            if (Double.valueOf(a.get("c_lat").toString()) > 0) {
                LocationTrans.TransPoint point = LocationTrans.bd_decrypt(Double.valueOf(a.get("c_lat").toString()), Double.valueOf(a.get("c_lng").toString()));
                a.put("c_lat", point.latitude);
                a.put("c_lng", point.longitude);
            }
        });
        return JsonResult.ok(res);
    }

    @PostMapping(value = "/getShortList")
    @ApiOperation(value = "获取简短的树木信息")
    public JsonResult<List<Map<String, Object>>> getShortList() {
//        QueryWrapper<GreTreeFamous> wrapper=new QueryWrapper<GreTreeFamous>();
//        wrapper.select("c_tree_id `id`,c_name `value`,c_code `code`");
//        wrapper.eq("c_db_status",0);
//        wrapper.le("c_famous_type_id",2);
        List<Map<String, Object>> res = iGreTreeFamousService.listMaps();
        return JsonResult.ok(res);
    }

    @ApiOperation(value = "审核状态")
    @GetMapping(value = "/updateState")
    public JsonResult<?> updateState(Integer id, Boolean state) {
        GreTreeFamous greTreeFamous = new GreTreeFamous();
        greTreeFamous.setId(id);
        greTreeFamous.setState(state);
        iGreTreeFamousService.saveOrUpdate(getUserId(), greTreeFamous);
        return JsonResult.ok(true);
    }

    @ApiOperation(value = "获取群落信息")
    @GetMapping(value = "/getCommunity")
    public JsonResult<?> getCommunityByCode(String communityCode) {
        Community community = communityService.getEntityByColumn("c_code", communityCode);
        return JsonResult.ok(community);
    }

    @ApiOperation(value = "按类型生成二维码列表")
    @GetMapping(value = "/getListForQRCodeByType")
    public JsonResult<?> getListForQRCodeByType(Integer type) {
        switch (type) {
            case 1:
                return JsonResult.ok(iGreTreeFamousService.getListForQRCode(1));
            case 2:
                return JsonResult.ok(iGreTreeFamousService.getListForQRCode(2));
            case 3:
                return JsonResult.ok(communityService.getList());
            default:
                return null;
        }
    }

    @ApiOperation(value = "获取群落信息编号")
    @GetMapping(value = "/getCommunityCode")
    public JsonResult<?> getCommunityCode() {
//        QueryWrapper<Community> wrapper=new QueryWrapper<Community>();
//        wrapper.select("c_code");
//        wrapper.eq("c_db_status",0);
        List<Map<String, Object>> list = communityService.listMaps();
        return JsonResult.ok(list);
    }

    @ApiOperation(value = "获取群落列表")
    @PostMapping(value = "/getCommunityList")
    public JsonResult<?> getCommunityList(@RequestBody CommunityQuery query) {
        DataPager<CommunityVO> list = communityService.listPage(query);
        return JsonResult.ok(list);
    }

    @GetMapping("/deleteCommunity")
    @ApiOperation(value = "批量删除")
    public JsonResult<?> deleteCommunity(String ids) {
        SysUser user = getUser();
        String[] idArray = ids.split(",");
        List<String> idList = Arrays.asList(idArray);
        idList.forEach(
                id -> {
//                    UpdateWrapper<Community> updateWrapper = new UpdateWrapper<>();
//                    updateWrapper.set("c_db_status", 1)
//                            .eq("c_id", id);
                    Community community = new Community();
                    community.setId(Integer.parseInt(id));
                    community.setDbStatus(true);
                    communityService.saveOrUpdate(getUserId(), community);
                });
        return JsonResult.ok("删除成功");
    }

    @PostMapping("/insertCommunity")
    @ApiOperation(value = "新增或修改群落")
    public JsonResult<?> insertCommunity(@RequestBody Community community) {

        community.setDbStatus(false);
        communityService.saveOrUpdate(getUserId(), community);
        return JsonResult.ok("操作成功");
    }


    @PostMapping(value = "/getCodeList")
    @ApiOperation(value = "获取简短的树木信息")
    public JsonResult<List<Map<String, Object>>> getCodeList() {
        List<Map<String, Object>> res = greTreeFamousDao.getCodeList();
        return JsonResult.ok(res);
    }

    @ApiOperation("excel数据导入")
    @PostMapping("/analysisExcel")
    public JsonResult<?> analysisExcel(@RequestBody MultipartFile file) {
        return greTreeFamousLogic.analysisExcel(file);
    }

    @ApiOperation("导入数据")
    @PostMapping("/importExcel")
    public JsonResult<?> importExcel(@RequestBody List<GreTreeFamousVO> treeFamousVOList) {
        return greTreeFamousLogic.importExcel(treeFamousVOList);
    }
}
